/*
 * @Description: 
 * @Author: ye_xf
 * @Date: 2022-07-26 13:43:47
 * @LastEditTime: 2022-08-05 15:26:42
 * @LastEditors: ye_xf
 * @Reference: 
 */
import * as types from './actionTypes'
import * as mutationTypes from '../Mutation/mutationTypes'
import { getEnums } from '@/api/app'
import { login } from '@/api/login'
import { getUser, getPermissions } from '@/api/user'
import storage from '@/utils/storage'
import { PORTAL_ID } from "@/config/app/develop"

const actions = {
  //用户登录
  [types.USER_LOGIN]({ commit }, data) {
    return new Promise((resolve, reject) => {
      login(data)
        .then(async (res) => {
          if (res) {
            //加载用户信息
            storage.set('username', res.userName)
            storage.set('userFullname', res.userFullname)
            storage.set('access_token', res.access_token)
            storage.set('userId', res.id)
            commit(mutationTypes.SET_USER_INFO, res)
            if (res) {
              return resolve(res)
            }
          }
          reject('')
        })
        .catch((e) => {
          reject(e)
        })
    })
  },

  //获取枚举
  [types.GET_ENUMS]({ commit }) {
    return new Promise((resolve, reject) => {
      getEnums()
        .then((res) => {
          if (res.status && res.data) {
            commit(mutationTypes.SET_ENUM, res.data)
          }
          resolve(res)
        })
        .catch((err) => reject(err))
    })
  },

  //获取语言资源
  [types.GET_LANG]({ commit }, lang_config) {
    getLang(lang_config).then(res => {
      if (res.status && res.data) {
        commit(mutationTypes.SET_ONLINE_LANG, { ...res.data })
      }
    }).catch(() => { })
  },

  [types.GET_PERMISSIONS]({ state, commit }, menuId) {
    //获取按钮权限
    return new Promise((resolve, reject) => {
      getPermissions(menuId).then(res => {
        if (res.status) {
          commit(mutationTypes.SET_PERMISSION, { key: menuId, value: res.data })
        }
        resolve(true)
      }).catch(() => {
        resolve(true)
      })
    })
  },

  //门户切换
  [types.CHANGE_PORTAL]({ commit }, portal) {
    commit(mutationTypes.CLEAN_VIEWS)
    commit(mutationTypes.CLEAN_ROUTE)
    commit(mutationTypes.CLEAN_PERMISSION)
    commit(mutationTypes.CLEAN_PERMISSION_QUEUE)
    commit(mutationTypes.UPDATE_PORTAL, portal)
  },

  //根据门户获取用户信息
  [types.UPDATE_USER]({ commit }, portalId = PORTAL_ID) {
    return new Promise((resolve, reject) => {
      getUser({ userName: `${storage.get('username')}`, portalId }).then(res => {
        if (res.status && res.data) {
          commit(mutationTypes.SET_USER_INFO, res.data)
        }
        resolve(res)
      }).catch(e => resolve(e))
    })
  },
}

export default actions